<template>
  <div>
    <h3>个人中心</h3>
    <p>pinia: {{ name }} - {{ age }} - {{ newAge }} - {{ newName }}</p>
    <p>pinia: {{ num }} - {{ newNum }}</p>
    <p>
      pinia: {{ store.homeName }} - {{ store.homeAge }} - {{ store.homeArr }}
    </p>
    <button @click="patchChange">批量修改state</button>
    <p>购物车: {{ cartStore.cartNum }}</p>
    <p>购物车: {{ cartStore.cartNum }}</p>
    <p>getters: {{ cartStore.cartNumStr }}</p>
    <p>getters: {{ cartStore.cartNumStr }}</p>
    <p>getters: {{ cartStore.cartNumStr }}</p>
    <p>getters: {{ cartStore.cartNumStr }}</p>
    <p>getters: {{ cartStore.cartNumStr }}</p>
    <p>getters: {{ cartStore.cartNumStr }}</p>
    <button @click="setNum">num++</button>
  </div>
</template>

<script>
import { mapState } from "pinia";
import useHome from "@/stores/useHome";
import useCart from "@/stores/useCart";
export default {
  name: "Vue3TsCourseProfile",
  data() {
    return {
      store: null,
      cartStore: null,
    };
  },
  created() {
    this.store = useHome();
    this.cartStore = useCart();
  },
  methods: {
    patchChange() {
      // this.store.$patch({
      //   homeName: "消化",
      //   homeAge: 100,
      //   homeArr: [...this.store.homeArr, 4, 5, 6],
      // }); // 批量修改：一次修改多个state，视图只渲染一次。
      // homeStore.homeName = "小红";
      // homeStore.homeAge = 20;
      // homeStore.homeSex = "男";
      // homeStore.homeClass = 200;

      this.store.$patch(state => {
        state.homeName = "小王";
        state.homeAge = 200;
        state.homeArr.push(4, 5, 6);
      });
    },
    setNum() {
      this.cartStore.addCartNum();
      // let num = this.cartStore.cartNum;
      // if (num < 1) {
      //   console.log("至少是一件");
      // } else {
      //   if (num < 10) {
      //     this.cartStore.cartNum++;
      //   } else {
      //     console.log("库存不够");
      //   }
      // }
    },
  },
  computed: {
    ...mapState(useHome, {
      name: "homeName",
      age: "homeAge",
      newAge: store => store.homeAge * 2,
      newName: store => store.homeName + "-",
    }),
    ...mapState(useCart, {
      num: "cartNum",
      newNum: store => `价格是:${store.cartNum}元/件`,
    }),
  },
};
</script>
